<!-- 

  ____        _                         _____
 |  _ \      | |                       / ____|
 | |_) | __ _| | __ _ _ __   ___ ___  | |     __ _ _ __
 |  _ < / _` | |/ _` | '_ \ / __/ _ \ | |    / _` | '__|
 | |_) | (_| | | (_| | | | | (_|  __/ | |___| (_| | |
 |____/ \__,_|_|\__,_|_| |_|\___\___|  \_____\__,_|_|
   _____           _           _   ____         __     __  _    _                 _     _
  / ____|         | |         | | |  _ \        \ \   / / | |  | |               | |   | |
 | |     ___  __ _| |_ ___  __| | | |_) |_   _   \ \_/ ___| |__| | __ _ _ __ ___ | | __| |
 | |    / _ \/ _` | __/ _ \/ _` | |  _ <| | | |   \   / _ |  __  |/ _` | '__/ _ \| |/ _` |
 | |___|  __| (_| | ||  __| (_| | | |_) | |_| |    | |  __| |  | | (_| | | | (_) | | (_| |
  \_____\___|\__,_|\__\___|\__,_| |____/ \__, |    |_|\___|_|  |_|\__,_|_|  \___/|_|\__,_|
                                          __/ |
                                         |___/
  Copyright (c) 2024 YeHarold

  -->

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<title>BalanceCar</title>
	<meta name="viewport" content="width=device-width, initial-scale=0.5, maximum-scale=0.5" />
	<script src="./js/nipplejs.js"></script>
	<script src="./js/iro.min.js"></script>
	<script src="./js/ping.js"></script>
	<link type="text/css" rel="stylesheet" href="./css/index.css" />
</head>

<body>
	<div id="connectStatus">BalanceCar连接中..</div>

	<div class="justify-battery">
		<svg t="1720362977145" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
			p-id="10604" width="150" height="150">
			<path id="battery-level" d="M50,400 h0 v200 h-0 z" fill="#2ECC71" />
			<path
				d="M877.728 352H62.688C28.064 352 0 374.624 0 402.528v218.976C0 649.376 28.064 672 62.688 672h815.04c34.624 0 62.688-22.624 62.688-50.528v-218.976c0-27.872-28.064-50.496-62.688-50.496zM896 623.744c0 9.472-9.44 17.216-21.056 17.216H53.088c-11.648 0-21.088-7.712-21.088-17.216v-223.488c0-9.504 9.44-17.216 21.088-17.216h821.856c11.616 0 21.056 7.712 21.056 17.216v223.488zM961.312 453.056c34.624 0 62.688 22.624 62.688 50.56v16.8c0 27.904-28.064 50.56-62.688 50.56v-117.92z"
				p-id="10606" fill="#d9d9d9">
			</path>
		</svg>
	</div>
	<div class="justify">
		<div id="picker"></div>
		<div id="ipconfig">
			<input type="text" placeholder="192.168.1.80" id="BalanceCarIP">
		</div>
	</div>
	<div class="justify">
		<button class="button" id="RGBButton">RGB</button>
	</div>
	<div class="justify">
		<div>
			<button class="button" id="plusButton">+</button>
			<span id="MPU">MPU:+0.00</span>
			<button class="button" id="minusButton">-</button>
		</div>
	</div>
	<div class="justify">
		<button class="button" id="PowerOff">OFF</button>
	</div>

	<div class="box" id="joystick_zone">
		<div class="img">
			<div id="joystick"></div>
		</div>
	</div>
</body>

<script>
	// ---------------连接WiFi----------------------------------------------------------------------
	var url = "http://192.168.221.80";

	let isLongPressTriggered = false;
	let pressTimer = null;

	const carIP = document.getElementById('BalanceCarIP');
	const connectStatus = document.getElementById('connectStatus');
	const config = document.getElementById('ipconfig');
	var IPconfig = true;

	//长按
	connectStatus.addEventListener('touchstart', function (e) {
		clearTimeout(pressTimer);
		pressTimer = setTimeout(function () {
			isLongPressTriggered = true;
			IPconfig = !IPconfig;
			if (IPconfig) {
				config.style.display = "block";
				// url = "http://" + carIP.value;
				// console.log(url);
			}
			else {
				config.style.display = "none";
				url = "http://" + carIP.value;
			}

		}, LONG_PRESS_THRESHOLD);
		e.preventDefault();
	});



	//点击
	var clickConfig = false;
	connectStatus.addEventListener('touchend', function (e) {
		clearTimeout(pressTimer);
		if (!isLongPressTriggered) {
			clickConfig = !clickConfig;
			if (clickConfig) {
				config.style.display = "block";
				// url = "http://" + carIP.value;
				// console.log(url);
			}
			else {
				config.style.display = "none";
				url = "http://" + carIP.value;
			}
		}
		isLongPressTriggered = false;
	});


	connectStatus.addEventListener('touchend', cancelPress);
	connectStatus.addEventListener('touchcancel', cancelPress);
	connectStatus.addEventListener('touchmove', cancelPress)

	// var url = "http://192.168.1.5";
	let connectTimer = null;

	function ConnectBalanceCar() {
		clearInterval(connectTimer);
		fetch(url + "/connect", {
			method: "GET"
		}).then((response) => {
			if (response.ok) {
				document.getElementById('connectStatus').innerHTML = "BalanceCar连接成功";
				clearInterval(connectTimer);
			} else {
				document.getElementById('connectStatus').innerHTML = "BalanceCar连接中..";
				connectTimer = setInterval(ConnectBalanceCar, 5000);
			}
		}).catch((error) => {
			document.getElementById('connectStatus').innerHTML = "BalanceCar连接失败";
			connectTimer = setInterval(ConnectBalanceCar, 5000);
		});
	}

	ConnectBalanceCar();


	const PowerButton = document.getElementById('PowerOff');
	PowerButton.addEventListener('click', function () {
		fetch(url + "/poweroff", {
			method: "GET"
		});
	});

	//-----------------Battery ----------------------------------------------------------------

	var voltage = 3303;

	function updateBatteryLevel() {
		// 确保电量在0到100之间

		fetch(url + "/voltage", {
			method: "GET"
		}).then((res) => {
			return res.text();

		}).then((res) => {
			voltage = Number(res)
		})

		var percentage = 1.0 - (3295 - voltage) / 292;
		if (percentage >= 1) {
			percentage = 1.0;
		} else if (percentage <= 0) {
			percentage = 0;
		}
		var batteryWidth = 800; // 电池的总宽度
		var levelWidth = batteryWidth * percentage; // 电量条的宽度

		var batteryLevelPath = document.getElementById('battery-level');
		batteryLevelPath.setAttribute('d', `M60,410 h${levelWidth} v200 h-${levelWidth} z`);
		if (percentage < 0.3) {
			batteryLevelPath.setAttribute('fill', '#FF5733'); //#2ECC71  #FF5733
		} else {
			batteryLevelPath.setAttribute('fill', '#2ECC71');
		}


	}

	setInterval(function () {
		updateBatteryLevel();
	}, 2500); // 每秒更新一次

	//-----------------MPU矫正----------------------------------------------------------------
	var distance = +0.00;

	let incrementTimer = null;
	const LONG_PRESS_THRESHOLD = 200;


	const minusButton = document.getElementById('minusButton');
	const plusButton = document.getElementById('plusButton');
	const mpu = document.getElementById('MPU');

	function updateDisplay() {
		if (distance > 0) {
			mpu.textContent = "MPU:+" + distance.toFixed(2);
		} else if (distance < 0) {
			mpu.textContent = "MPU:" + distance.toFixed(2);
		}
	}

	updateDisplay();

	function MPUoffsetMinus(step) {
		distance = distance - step;

		fetch(url + "/mpuset?direction=mpu&distance=" + distance.toFixed(2).toString(), {
			method: "GET"
		});

		updateDisplay();
	}

	function MPUoffsetPlus(step) {
		distance = distance + step;

		fetch(url + "/mpuset?direction=mpu&distance=" + distance.toFixed(2).toString(), {
			method: "GET"
		});
		updateDisplay();
	};


	function cancelPress() {
		clearTimeout(pressTimer);
		clearInterval(incrementTimer);
	}

	//长按
	plusButton.addEventListener('touchstart', function (e) {
		clearTimeout(pressTimer);
		clearInterval(incrementTimer);
		pressTimer = setTimeout(function () {

			isLongPressTriggered = true;
			incrementTimer = setInterval(() => {
				MPUoffsetPlus(1);
			}, 35);
		}, LONG_PRESS_THRESHOLD);
		e.preventDefault();
	});


	minusButton.addEventListener('touchstart', function (e) {
		clearTimeout(pressTimer);
		clearInterval(incrementTimer);
		pressTimer = setTimeout(function () {

			isLongPressTriggered = true;
			incrementTimer = setInterval(() => {
				MPUoffsetMinus(1);
			}, 35);
		}, LONG_PRESS_THRESHOLD);
		e.preventDefault();
	});

	//点击
	plusButton.addEventListener('touchend', function (e) {
		clearTimeout(pressTimer);
		if (!isLongPressTriggered) {
			MPUoffsetPlus(0.1);

		}
		isLongPressTriggered = false;
	});

	minusButton.addEventListener('touchend', function (e) {
		clearTimeout(pressTimer);
		if (!isLongPressTriggered) {
			MPUoffsetMinus(0.1);

		}
		isLongPressTriggered = false;
	});

	// 取消长按事件
	plusButton.addEventListener('touchend', cancelPress);
	plusButton.addEventListener('touchcancel', cancelPress);
	plusButton.addEventListener('touchmove', cancelPress);

	minusButton.addEventListener('touchend', cancelPress);
	minusButton.addEventListener('touchcancel', cancelPress);
	minusButton.addEventListener('touchmove', cancelPress);
	// ----------------------------RGB--------------------------------------------------------
	const picker = document.getElementById('picker');
	var color = null;
	var RGBButtonStatus = false;

	var colorPicker = new iro.ColorPicker("#picker", {
		width: 500,
		color: "#c5ff23",
	});

	colorPicker.on('color:change', setColor);

	function setColor() {
		color = "{" + colorPicker.color.red + "," + colorPicker.color.green + "," + colorPicker.color.blue + "}";
		// console.log(color);
	}


	const RGBButton = document.getElementById('RGBButton');
	const joystick_zone = document.getElementById('joystick_zone');

	//长按
	RGBButton.addEventListener('touchstart', function (e) {
		clearTimeout(pressTimer);
		pressTimer = setTimeout(function () {
			isLongPressTriggered = true;
			RGBButtonStatus = !RGBButtonStatus;

			if (RGBButtonStatus) {
				picker.style.display = "block";
				joystick_zone.style.display = "none"; //none
			} else {

				joystick_zone.style.display = "flex";
				picker.style.display = "none"; //none

				fetch(url + "/rgb?color=" + color + "&status=on", {
					method: "GET"
				});
			}

		}, LONG_PRESS_THRESHOLD);
		e.preventDefault();
	});


	var RGBOnOff = false;

	//点击
	RGBButton.addEventListener('touchend', function (e) {
		clearTimeout(pressTimer);
		if (!isLongPressTriggered) {
			RGBOnOff = !RGBOnOff;

			if (RGBOnOff) {
				var r = Math.floor(Math.random() * 256);
				var g = Math.floor(Math.random() * 256);
				var b = Math.floor(Math.random() * 256);
				color = "{" + r + "," + g + "," + b + "}";
				fetch(url + "/rgb?color=" + color + "&status=on", {
					method: "GET"
					// console.log(color);
				})
			} else {
				fetch(url + "/rgb?color={0,0,0}&status=off", {
					method: "GET"
				})
			}


		}
		isLongPressTriggered = false;
	});


	RGBButton.addEventListener('touchend', cancelPress);
	RGBButton.addEventListener('touchcancel', cancelPress);
	RGBButton.addEventListener('touchmove', cancelPress)
	//----------------------------遥控--------------------------------------------------------------

	function Joystick(opt) {
		if (!opt.zone) return;
		var disabledColor = opt && opt.disabledColor || true;

		this.options = {
			mode: opt && opt.mode || 'static',
			size: opt && opt.size || 500,
			color: disabledColor ? '  #706b6b' : (opt && opt.color || 'gray'),
			position: opt && opt.position || {
				left: '50%',
				top: '50%'
			},
			zone: opt && opt.zone
		};
		this.distance = 0;
		this.angle = null;
		this.time = null;
	}

	Joystick.prototype.init = function () {
		var manager = nipplejs.create(this.options);
		this.manager = manager;
		this._on();
		return this;
	}

	Joystick.prototype._on = function () {
		var me = this;
		this.manager
			.on('start', function (evt, data) {
				me.time = setInterval(() => {
					me.onStart && me.onStart(me.distance, me.angle);
				}, 80);
			})
			.on('move', function (evt, data) {
				if (data.direction) {
					me.angle = data.direction.angle;
					me.distance = data.distance;
				}
			})
			.on('end', function (evt, data) {
				for (var i = 0; i < 3; i++) {
					fetch(url + "/move?direction=stop" + "&distance=0.00", {
						method: "GET"
					});
				}
				clearInterval(me.time);
				me.onEnd && me.onEnd();
			});
	}

	new Joystick({
		zone: document.getElementById("joystick"),
	})
		.init()
		.onStart = function (distance, angle) {

			if (angle) {
				fetch(url + "/move?direction=" + angle + "&distance=" + (100 * distance / 250).toFixed(2).toString(), {
					method: "GET"
				});
			}
		}
</script>

</html>